<template>
	<view class="add-member">
		<u-form labelPosition="left" :model="formData" :rules="rules" labelWidth="240rpx" ref="form">
			<view class="form-label-top margin-top-3">
				<u-form-item label="姓名" prop="name" borderBottom required>
					<view class="d-flex justify-space-between">
						<view>
							<u-input v-model="formData.name" placeholder="请输入姓名" border="none" @input="fpNumInput"/>

							<view style="margin-top: 36rpx;">
								<u-radio-group v-model="formData.sex">
									<u-radio label="男" :name="1" />
									<u-radio label="女" :name="0" customStyle="margin-left: 60rpx;" />
								</u-radio-group>
							</view>

						</view>
						<image @click="avatarimage" v-if="url_phoneimg != ''" src="https://jiangsudiantuo2022.oss-cn-hangzhou.aliyuncs.com/img/d486f37c1f8b7458c01bc2243e0333f252f2b33a.png" mode=""  style="width: 30rpx; height: 30rpx;position: absolute;right: 20rpx;z-index: 999;"></image>
						<image style="width: 144rpx; height: 144rpx;" v-if="url_phoneimg != ''"
							:src="url_phoneimg">
						</image>
						<u-upload v-else :fileList="fileList1" name="1" width="70" height="70" @afterRead="afterRead"
							@delete="deletePic" multiple :maxCount="1" />

					</view>
				</u-form-item>
			</view>
			<u-form-item label="联系电话" prop="phone" required>
				<u-input v-model="formData.phone" placeholder="请输入联系电话" border="none" type="number" />
			</u-form-item>
			<u-form-item label="身份证号" prop="idcard" borderBottom required>
				<u-input v-model="formData.idcard" placeholder="请输入身份证号" border="none" type="idcard" />
			</u-form-item>
			<u-form-item label="位置" prop="position" borderBottom required>
				<u-input v-model="formData.position" placeholder="请输入您在球队中司职位置" border="none" />
			</u-form-item>
			

			<view class="group">
				<u-form-item label="紧急联系人" prop="urgentContacts" borderBottom>
					<u-input v-model="formData.urgentContacts" placeholder="请输入紧急联系人" border="none" />
				</u-form-item>
				<u-form-item label="紧急联系人电话" prop="urgentContactsPhone" borderBottom>
					<u-input v-model="formData.urgentContactsPhone" placeholder="请输入紧急联系人电话" border="none"
						type="number" />
				</u-form-item>
				<!-- <u-form-item label="亲属关系" prop="kinship" borderBottom>
					<u-input v-model="formData.kinship" placeholder="请输入亲属关系" border="none" />
				</u-form-item> -->

				<u-form-item label="亲属关系" prop="kinship">
					<view @click="showKinshipPicker = true" class="flex-between">
						<u-text :text="formData.kinship" v-if="formData.kinship" color="#303133"></u-text>
						<u-text text="请选择亲属关系" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx" customStyle="margin-left: 30rpx;">
						</u-icon>
					</view>
					<u-picker :show="showKinshipPicker" :columns="columns.kinship"
						@confirm="confirmPicker($event, 'kinship')" @cancel="showKinshipPicker = false" />
				</u-form-item>
			</view>

			<view class="group">
				<!-- <u-form-item label="生日" prop="birthday" borderBottom>
					<view @click="showBirthdayPicker = true" class="flex-between">
						<u-text :text="formData.birthday" v-if="formData.birthday" color="#303133"></u-text>
						<u-text text="请选择生日" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx"></u-icon>
					</view>
					<u-datetime-picker
						v-model="defaultBirthday"
						:show="showBirthdayPicker"
						mode="date"
						:minDate="minDate"
						:maxDate="maxDate"
						@confirm="confirmBirthday"
						@cancel="showBirthdayPicker = false"
					/>
				</u-form-item> -->
				
				<!-- <u-form-item label="身份" prop="identity" borderBottom>
					<view @click="showIdentityPicker = true" class="flex-between">
						<u-text :text="formData.identity" v-if="formData.identity" color="#303133"></u-text>
						<u-text text="请选择身份" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx"></u-icon>
					</view>
					<u-picker
						:show="showIdentityPicker"
						:columns="columns.identity" 
						@confirm="confirmPicker($event, 'identity')"
						@cancel="showIdentityPicker = false"
					/>
				</u-form-item> -->

				
				<u-form-item label="身高" prop="height" borderBottom>
					<u-input v-model="formData.height" placeholder="请输入身高" border="none" type="number" />
				</u-form-item>
				<u-form-item label="体重" prop="weight" borderBottom>
					<u-input v-model="formData.weight" placeholder="请输入体重" border="none" type="number" />
				</u-form-item>
				<u-form-item label="服装尺寸" prop="clothingSize" borderBottom>
					<u-input v-model="formData.clothingSize" placeholder="请输入服装尺寸" border="none" type="number" />
				</u-form-item>

				<!-- 	<u-form-item label="服装尺寸" prop="clothingSize" borderBottom>
					<view @click="showClothingSizePicker = true" class="flex-between">
						<u-text :text="formData.clothingSize" v-if="formData.clothingSize" color="#303133"></u-text>
						<u-text text="请选择" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx"></u-icon>
					</view>
					<u-picker :show="showClothingSizePicker" :columns="columns.clothingSize"
						@confirm="confirmPicker($event, 'clothingSize')" @cancel="showClothingSizePicker = false" />
				</u-form-item> -->
				<!-- <u-form-item label="所属组织" prop="organization" borderBottom>
					<u-input v-model="formData.organization" placeholder="请输入所属组织" border="none" type="number" />
				</u-form-item> -->
				<!-- <u-form-item label="所属组织" prop="organization" borderBottom required>
					<view @click="showOrganizationPicker = true" class="flex-between">
						<u-text :text="formData.organization" v-if="formData.organization" color="#303133"></u-text>
						<u-text text="请选择" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx"></u-icon>
					</view>
					<u-picker
						:show="showOrganizationPicker"
						:columns="columns.organization" 
						@confirm="confirmPicker($event, 'organization')"
						@cancel="showOrganizationPicker = false"
					/>
				</u-form-item> -->
				<u-form-item label="购买保险" prop="insurance">
					<view @click="showInsurancePicker = true" class="flex-between">
						<u-text :text="formData.insurance" v-if="formData.insurance" color="#303133"></u-text>
						<u-text text="请选择" v-else color="#c0c4cc"></u-text>
						<u-icon name="arrow-right" color="#BEBEBE" size="28rpx"></u-icon>
					</view>
					<u-picker :show="showInsurancePicker" :columns="columns.insurance"
						@confirm="confirmPicker($event, 'insurance')" @cancel="showInsurancePicker = false" />
				</u-form-item>
			</view>
		</u-form>

		<view class="bottom-add-btn">
			<u-button text="确认添加" shape="circle" @click="add"
				color="linear-gradient(0deg, rgb(47, 117, 250) 0%, rgb(82, 142, 255) 100%)"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		formatDate,
		serialize
	} from '@/utils/util.js';
	const venues = require("@/api/venues/venues.js");
	export default {
		data() {
			return {
				options: {},
				formData: {
					sex: 1,
					name: '', //名字
					avatar: '', //头像
					sex: '', //性别
					phone: '', //联系电话
					join_level: '', //参赛等级
					dqid: '', //城市
					organization: '', //所属团队
					good_at: '', //擅长项目
					position: '', //场上位置
					cloth_code: '', //球衣号码
					clothingSize: '', //尺码
					shoes_size: '', //鞋码
					personal_info: '', //个人简介
					urgentContacts: '', //紧急联系人
					urgentContactsPhone: '', //紧急联系人电话
					kinship: '', //亲属关系
					idcard: '', //身份证号码
					identity: '', //身份
					height: '', //身高
					weight: '', //体重
					insurance: '', //保险
					app_id: '', //
					id: '',
					showKinshipPicker: false,
					columnn: {
						kinship: [
							// ['母亲','12','23'],
							["父亲", "母亲", "爷爷", "奶奶", "其他"]
						],
						
					},
				},
				rules: {
					'formData.name': {
						required: true,
						message: '请输入姓名',
						trigger: ['change'],
					},
					'formData.phone': {
						required: true,
						message: '请输入联系电话',
						trigger: ['change'],
					}
				},
				venue_thumb: 'https://jiangsudiantuo2022.oss-cn-hangzhou.aliyuncs.com/img/e95069e70f384ec5b6c862c0117c23600bcbeb23.png',
				showKinshipPicker: false,
				showBirthdayPicker: false,
				showIdentityPicker: false,
				showClothingSizePicker: false,
				showOrganizationPicker: false,
				showInsurancePicker: false,
				columns: {
					identity: [
						[]
					],
					kinship: [
						["父亲", "母亲", "爷爷", "奶奶", "其他"]
					],
					clothingSize: [
						['XL', 'L', 'M', 'S']
					],
					insurance: [
						['是', '否']
					]
				},
				minDate: new Date(new Date().getFullYear() - 100, 0, 1).getTime(),
				maxDate: Date.now(),
				defaultBirthday: new Date(new Date().getFullYear() - 20, 0, 1).getTime(),
				fileList1: [],
				url_phone: '',
				url_phoneimg:'',
				resulturl: '',
				shi:'是',
				fo:'否'
			}
		},
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			if (option.type != 1) {
				const item = JSON.parse(decodeURIComponent(option.item1));
				if (option.type != 1) {
					this.formData.id = item.id
					this.formData.name = item.name
					this.formData.phone = item.phone
					this.formData.position = item.position
					this.formData.idcard = item.sfzhm
					this.formData.sex = item.sex
					this.formData.kinship = item.relation
					this.formData.height = item.height
					this.formData.weight = item.weight
					this.formData.clothingSize = item.size
					this.formData.urgentContactsPhone = item.special_phone
					this.formData.urgentContacts = item.special_person
					this.url_phoneimg = item.avatar
					if (item.is_buy_insure === 0) {
						this.formData.insurance = this.fo
					} else if(item.is_buy_insure === 1){
						this.formData.insurance = this.shi
					}
					
					// this.fileList1 = JSON.parse(item.avatar)
					// this.formData.insurance = item.is_buy_insure
				}
			}
		},
		onReady() {
			// this.$refs.form.setRules(this.rules);
		},
		methods: {
			fpNumInput(e) {
				console.log(e,'222')
				// const o = e.target;
				const inputRule =/[^\u4E00-\u9FA5]/g
				this.$nextTick(function() {
					this.formData.name = e.replace(inputRule, '');
					
				})
			},
			avatarimage(){
				this.url_phoneimg = ''
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])
				}
			},
			// confirmPicker({
			// 	value
			// }, key) {
			// 	this.formData[key] = value.join('');
			// 	this.formData.kinship = this.formData[key]
				
			// 	// this.itemlist.forEach(item =>{
			// 	// 	// itemArr.push(item.club_name)
			// 	// 	if (this.userInfo.kinship == item.club_name) {
			// 	// 		this.userInfo.kin_s = item.id
			// 	// 	} 
			// 	// })
			// 	this[`show${key[0].toUpperCase() + key.slice(1)}Picker`] = false;
			// },
			
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				this.resulturl = url
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://sass-test.doit10019.com/api/upload/uploadOneImage', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							// user: 'test',
							project_id: getApp().globalData.projectId,
							app_id: this.$https.weixinAppId,

						},
						header: {
							'content-type': 'multipart/form-data'
						},
						success: (res) => {
							let result = JSON.parse(res.data);
							this.url_phone = result.data.url
							setTimeout(() => {
								resolve(this.url_phone)
							}, 1000)
						}
					});
				})
			},
			confirmBirthday({
				value
			}) {
				this.formData.birthday = formatDate(value, 'YYYY-MM-DD');
				this.showBirthdayPicker = false;
			},
			confirmPicker({
				value
			}, key) {
				this.formData[key] = value.join('');
				// if (this.formData[key] == '是') {
				// 	this.formData.insurance = 1
				// } else{
				// 	this.formData.insurance = 0
				// }
				this[`show${key[0].toUpperCase() + key.slice(1)}Picker`] = false;
			},
			async add() {
				if (this.url_phoneimg != '') {
					this.url_phone = this.url_phoneimg
				} 
				if (this.formData.insurance == this.shi) {
					this.formData.insurance = 1
				} else if (this.formData.insurance == this.fo){
					this.formData.insurance = 0
				} else {
					this.formData.insurance = ''
				}
				let that = this
				if (this.formData.name == '') {
					uni.showToast({
						title: '请输入姓名',
						icon: 'none'
					})
				} else if (this.url_phone == '') {
					uni.showToast({
						title: '请上传头像',
						icon: 'none'
					})
				} 
				if (!that.formData.phone) { //判断如果手机号为空，提示用户输入手机号
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return
				}
				let idreg = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
				if (!that.formData.idcard) { //判断如果手机号为空，提示用户输入手机号
					uni.showToast({
						title: '请输入身份证号码',
						icon: 'none'
					})
					return
				} else if (!idreg.test(that.formData.idcard)) { //判断手机号格式时候正确
					uni.showToast({
						title: '请输入正确身份证号码',
						icon: 'none'
					})
					that.formData.idcard = ''
					return
				}

				 if (this.formData.position == '') {
					uni.showToast({
						title: '请输入位置',
						icon: 'none'
					})

				} else {
					// uni.showLoading({
					// 	title: "加载中",
					// });
					let params = {
						name: this.formData.name, //名字
						avatar: this.url_phone, //头像
						sex: this.formData.sex, //性别
						phone: this.formData.phone, //联系电话
						// team_id:this.formData.organization,//所属团队
						position: this.formData.position, //场上位置
						size: this.formData.clothingSize, //尺码
						special_person: this.formData.urgentContacts, //紧急联系人
						special_phone: this.formData.urgentContactsPhone, //紧急联系人电话
						relation: this.formData.kinship, //亲属关系
						sfzhm: this.formData.idcard, //身份证号码
						height: this.formData.height, //身高
						weight: this.formData.weight, //体重
						is_buy_insure: this.formData.insurance, //保险
						project_id: getApp().globalData.projectId,
						app_id: this.$https.weixinAppId,
						open_id: uni.getStorageSync("openid"),
						id: this.formData.id
					};
					let res = await venues.addmember(params);
					if (res.code === 1) {
						// uni.hideLoading();
						uni.navigateBack();

					}
					if (res.code === 0) {
						// uni.hideLoading();
						uni.showModal({
							title: res.info,
							// content: '是否确定删除！',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									that.formData.idcard = ''
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				}
				// try {
				// 	const valid = await this.$refs.form.validate();
				// 	if (valid) {

				// 		if (this.options.return) {
				// 			uni.navigateTo({
				// 				url: this.options.return + '?' + serialize(this.formData)
				// 			});
				// 		} else {
				// 			uni.navigateBack();
				// 		}
				// 	}
				// } catch (e) {

				// }
			}
		}
	}
</script>

<style lang="scss" scoped>
	.add-member {
		min-height: 100vh;
		background-color: #f6f6f6;
		padding-bottom: calc(150rpx + env(safe-area-inset-bottom));

		/deep/.u-form {
			.u-form-item {
				background-color: #fff;
			}

			.u-form-item__body {
				padding: 30rpx;
			}

			.group {
				margin-top: 20rpx;
			}

			.u-form-item__body__right__message {
				margin-left: 270rpx !important;
			}
		}
	}
</style>
